import * as fs from "fs"
import * as path from "path"
import { promisify } from "util"
import { UserProfile } from "../interface"
import { getDocDir, getLoginUser } from "../config"
import { APIContext, RouterDecorator } from "f2e-server3"
import { API, DIR_TYPE, stringify } from "../common"
import { hasAuthority } from "./app"

const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const mkdir = promisify(fs.mkdir)

export const getProfile = async (): Promise<UserProfile> => {
    const profileRoot = getDocDir()
    const profilePath = path.join(getDocDir(), DIR_TYPE.PROFILE)
    if (!fs.existsSync(profileRoot)) {
        await mkdir(profileRoot, { recursive: true })
    }
    if (!fs.existsSync(profilePath)) {
        await writeFile(profilePath, stringify({
            max_app_index: 1,
            apps: []
        }))
    }
    return JSON.parse(await readFile(profilePath, "utf8"))
}

export const updateProfile = async (profile: UserProfile) => {
    const profilePath = path.join(getDocDir(), DIR_TYPE.PROFILE)
    await writeFile(profilePath, stringify(profile))
}

export class ActionProfile {
    /**
     * 个人主页信息：包含站点列表
     */
    @RouterDecorator("api/profile")
    async profile(_ = {}, ctx: APIContext) {
        const loginUser = getLoginUser(ctx)
        if (!loginUser) {
            return API.error("未登录")
        }
        const profile = await getProfile()
        profile.apps = profile.apps.filter(item => hasAuthority(loginUser, item))
        return API.success({
            ...profile,
            ...loginUser,
        })
    }
}